import Q  from  './vendor/q';
import utils from './utils';
import Auth  from './bce-sdk-js/auth';
import Base64 from './vendor/base64';
function PolicyManager(options) {
    this.options = options;
    this._cache = {};
}
console.log('Base64.encode',Base64.encode('123456'));
PolicyManager.prototype.get = function (bucket) {
    var self = this;
    if (self._cache[bucket] != null) {
        return Q.resolve(self._cache[bucket]);
    }
    return Q.resolve(this._getImpl(bucket)).then(function (payload) {
        self._cache[bucket] = payload;
        return payload;
    });
};

PolicyManager.prototype._getImpl = function (bucket) {
    var bucketPolicy = utils.getDefaultPolicy(bucket);
    var options = this.options;
    if (options.bos_credentials && !options.uptoken) {
        // 如果没有 options.uptoken，说明不是 临时 ak 和 sk
        var credentials = options.bos_credentials;
        return this._getFromLocal(bucketPolicy, credentials);
    }
    return this._getFromRemote(bucketPolicy);
};

PolicyManager.prototype._getFromLocal = function (bucketPolicy, credentials) {
    var auth = new Auth(credentials.ak, credentials.sk);
    var policyBase64 = Base64.encode(JSON.stringify(bucketPolicy));
    var policySignature = auth.hash(policyBase64, credentials.sk);
    var policyAccessKey = credentials.ak;
    return {
        policy: policyBase64,
        signature: policySignature,
        accessKey: policyAccessKey
    };
};
/**
 * 从远程获取policy及签名
 */
PolicyManager.prototype._getFromRemote = function (bucketPolicy) {
    var options = this.options;
    var uptoken_url = options.uptoken_url;
    var timeout = options.uptoken_timeout || options.uptoken_jsonp_timeout;
    var deferred = Q.defer();
    wx.request({
        url : uptoken_url,
        dataType:'json',
        data:{
           policy: JSON.stringify(bucketPolicy)
        },
        header:{
          'content-type': 'application/x-www-form-urlencoded'
        },
        method:'POST',
        success:function(payload){
          var data = payload.data;
          if(data && typeof data === 'object'){
              if (data['policy']
                  && typeof data['policy'] === 'string'
                  && data['signature']
                  && typeof data['signature'] === 'string'
                  && data['accessKey']
                  && typeof data['accessKey'] ==='string'){
                  deferred.resolve(data);
              }else if(data['result'] && typeof data['result'] === 'object'){
                  var result = data['result'];
                  if (result['policy']
                      && typeof result['policy'] === 'string'
                      && result['signature']
                      && typeof result['signature'] === 'string'
                      && result['accessKey']
                      && typeof result['accessKey'] === 'string') {
                      deferred.resolve(result);
                  }
              }else{
                deferred.reject(new Error('Get policy signature fail'));
              }
          }else{
            deferred.reject(new Error('Get policy signature fail'));
          }
        },
        fail:function(){
            deferred.reject(new Error('Get policy signature timeout (' + timeout + 'ms).'));
        }
    });
    return deferred.promise;
};
export default PolicyManager;
